import { Upload, FilesType, UploadFileInfoType, UploadUrls } from "@/api/interface/index";
import { PORT1 } from "@/api/config/servicePort";
import { useRequest } from "@/api";
import { ResultEnum } from "@/enums/httpEnum";
import dayjs from "dayjs";
const timeBase64 = btoa(`${dayjs().format("YYYY-MM-DD")}/${dayjs().format("YYYY-MM-DD")}`);
const http = useRequest({
  // 默认地址请求地址，可在 .env.** 文件中修改
  baseURL: window.staticConfig.uploadUrl,
  // 设置超时时间
  timeout: ResultEnum.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: true,
  headers: {
    "Authorize-Code": `d2dcc9eff6dd3b706489681a299f2c56a9d8678053e8ae0b0ed44937cca46adce6c8fe81db093fa95c9e98e1f939e911${timeBase64}`
  }
});
/**
 * @name 文件上传模块
 */
// 单文件上传
export const uploadImg = (params: FormData) => {
  return http.post<Upload.ResFileUrl>(PORT1 + `/file/upload`, params);
};

// 多文件上传
export const uploadImgs = (params: FormData) => {
  return http.post<Upload.ResFileUrl>(PORT1 + `/file/uploads`, params);
};

// 视频上传
export const uploadVideo = (params: FormData) => {
  return http.post<Upload.ResFileUrl>(PORT1 + `/file/upload/video`, params);
};

/**
 * 根据 md5 检查文件是否上传，若上传一半，则返回已上传的文件序号 listParts
 * @param md5
 * @returns
 */
export const checkFileByMd5 = (md5: string) => {
  return http.get<UploadFileInfoType>(`/files/multipart/check/${md5}`, {}, { isUpload: true });
};

/**
 * 根据文件信息初始化分片上传地址
 * @param data
 * @returns
 */
export const initMultPartFile = (data: UploadFileInfoType) => {
  return http.post<UploadUrls>(`/files/multipart/init`, data, { isUpload: true });
};

/**
 * 合并文件
 * @param md5
 * @returns
 */
export const mergeFileByMd5 = (md5: string) => {
  return http.post<string>(`/files/multipart/merge/${md5}`, {}, { isUpload: true });
};

/**
 * 分片下载
 * @param filename
 * @param bytes
 * @returns
 */
export const chunkDownloadFile = (path: string, bytes: string) => {
  return http.get(
    `/files/download`,
    {
      path
    },
    {
      responseType: "blob",
      isUpload: true,
      headers: {
        Range: bytes
      }
    }
  );
};

/**
 * 获取数据库文件列表
 */
export const fetchFileList = () => {
  return http.get<FilesType[]>(`/files/list`, {}, { isUpload: true });
};

/**
 * 生成预览链接
 */

export const downloadFile = (params: Object) => {
  return http.get(`/file/preview`, params);
};

/**
 * 生成下载链接
 */

export const downloadLink = (params: Object) => {
  return http.get(`/file/downloadLink`, params);
};

/**
 * 删除大文件
 */

export const deleteFileApi = (params: Object) => {
  return http.delete(`/files/delete`, params, { noLoading: true });
};
